/**
 * @Title: model.js
 * @Description: model
 * @author: Fanchao
 * @date: 2020/9/20 9:45 下午
 * @version V1.0
 */

import { pathToRegexp } from 'path-to-regexp';
import { message } from 'antd';
import {
    reqGetPcategory,
    reqDeletePcategory,
} from 'api/index';

export default {
    namespace: 'productCategoryList',
    state: {
        dataSource: [],
    },
    reducers: {
        setPcategoryList(state, { payload: dataSource }) {
            return { ...state, dataSource };
        },
    },
    effects: {
        * getPcategoryList({ payload}, { call, put, select }) {
            const result = yield call(reqGetPcategory,payload);
            if (result.status === 1) {
                const dataSource = result.data;
                yield put({
                    type: 'setPcategoryList',
                    payload: dataSource,
                });
            } else {
                message.error(result.message);
            }
        },

        * removeCategoryList({ payload, callback }, { call, put, select }) {
            const result = yield call(reqDeletePcategory, payload);
            if (result.status === 1) {
                if (callback && typeof callback === 'function') {
                    callback(result);
                }
            } else {
                message.error(result.message);
            }
        },

    },
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname }) => {
                if (pathToRegexp('/category-manage/p-category/list').exec(pathname)) {
                    dispatch({
                        type: 'getPcategoryList',
                        payload: {
                            limit: 10,
                            offset: 0,
                        }
                    });
                }
            });
        },
    },
};
